class PriorityQueue {
    constructor() {
        this.array = new Array();
        this.size = 0;
    }
    enQueue(key) {
        this.array[this.size++] = key; // 把插入的元素作为最后一个元素
        this.upAdjust(); // 把最后一个元素上浮
    }
    upAdjust() {
        let childIndex = this.size - 1;
        let parentIndex = Math.floor((childIndex - 1) / 2);
        const temp = this.array[childIndex];
        while (childIndex > 0 && temp > this.array[parentIndex]) {
            this.array[childIndex] = this.array[parentIndex];
            childIndex = parentIndex;
            parentIndex = Math.floor((childIndex - 1) / 2);
        }
        this.array[childIndex] = temp;
    }
    deQueue() {
        if (this.size <= 0) {
            throw new Error('队列已空');
        }
        const head = this.array[0]; // 获取最大元素（即堆顶）
        this.array[0] = this.array[--this.size]; // 最后一个元素移到堆顶
        this.downAdjust(); // 把堆顶元素下沉
        return head;
    }
    downAdjust() {
        let parentIndex = 0;
        let childIndex = 2 * parentIndex + 1;
        const temp = this.array[parentIndex];
        while (childIndex < this.size) {
            if (childIndex + 1 < this.size && this.array[childIndex] > this.array[childIndex + 1]) {
                childIndex++;
            }
            if (temp >= this.array[childIndex]) {
                break;
            }
            this.array[childIndex] = this.array[parentIndex];
            parentIndex = childIndex;
            childIndex = 2 * parentIndex + 1;
        }
        this.array[parentIndex] = temp;
    }
}

const priorityQueue = new PriorityQueue();
priorityQueue.enQueue(3);
priorityQueue.enQueue(5);
priorityQueue.enQueue(10);
priorityQueue.enQueue(2);
priorityQueue.enQueue(7);
console.log(priorityQueue.array);
console.log("出队元素：" + priorityQueue.deQueue());
console.log("出队元素：" + priorityQueue.deQueue());